#coding=utf-8
import os
import tornado.ioloop
import tornado.web
from pymongo import MongoClient
import json
from bson import json_util, ObjectId



class MainHandler(tornado.web.RequestHandler):
    def get(self):
        chapters = db['chapter_detail'].find({'bookName':u'盗墓笔记'}).sort("chapterId")
        # self.set_header("Content-Type", "application/json")
        # self.write(json.dumps(list(chapters), default=json_util.default))
        self.render("home.html", chapters=chapters)


class ChapterHandler(tornado.web.RequestHandler):
    def get(self, bookName, chapterId):
        # this_chapter = db['chapter_detail'].find_one(ObjectId(chapter))
        # read_chapter_data = {}
        # if this_chapter:
        #     read_chapter_data['this_chapter'] = this_chapter
        #     # read_chapter_data['prev_chapter'] = db['chapter_detail'].find_one({"chapterNum": this_chapter.get("chapterNum")-1})
        #     # read_chapter_data['next_chapter'] = db['chapter_detail'].find_one({"chapterNum": this_chapter.get("chapterNum")+1})
        # self.write(repr(bookName))
        chapter = db['chapter_detail'].find_one({'bookName': bookName, 'chapterId': int(chapterId)})
        #self.write(chapter.get('bookName'))
        self.render("test.html", chapter=chapter)


settings = {
    "template_path": os.path.join(os.path.dirname(__file__), "templates"),
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "debug": True
}

application = tornado.web.Application([
    (r"/", MainHandler),
    ("/(.*)/(\d{1,4})", ChapterHandler),
    ], **settings)

client = MongoClient()
db = client['QQxs']


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

